package com.blocks.mq.producer.example.service;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * @author lxd
 * @date 2020/12/5 9:23
 */
@Service
public class ExampleExcelReadService {

    public List<List<String>> readExcel(String path) {
        List<List<String>> result = new LinkedList<>();
        try (InputStream inp = new FileInputStream(path)) {
            Workbook wb = WorkbookFactory.create(inp);
            Sheet sheet = wb.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.rowIterator();
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();
                List<String> temp = new LinkedList<>();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    switch (cell.getCellTypeEnum()) {
                        case BOOLEAN:
                            temp.add(String.valueOf(cell.getBooleanCellValue()));
                            break;
                        case NUMERIC:
                            temp.add(String.valueOf(cell.getNumericCellValue()));
                            break;
                        case STRING:
                            temp.add(cell.getStringCellValue());
                            break;
                        default:
                    }
                }
                result.add(temp);
            }
        } catch (IOException | InvalidFormatException e) {
            e.printStackTrace();
        }
        return result;
    }

}
